﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.ApplicationServices;
using System.Text;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.Server;
using System.Web;
using System.Web.UI;


namespace Square.Layouts.Sq
{
    public partial class PeoplePage : LayoutsPageBase
    {
        string PropName = string.Empty;
        string _Manager = string.Empty;
        string _FirstName = string.Empty;
        string _LastName = string.Empty;
        string _userAccount = string.Empty;

        string strUrl = string.Empty;
        string _reqUserId = string.Empty;
        string _currentUserId = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            //UserControl을 Load한다.(경로: ~/_controltemplates/프로젝트명/UserControl파일명)
            Control cd1 = LoadControl("~/_controltemplates/Square/People_List.ascx");

            //Div영역에 UserControl을 추가한다.
            //dv_list.Controls.Add(cd1);
        }

        public void check_UserPropertyWS()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                if (Request.QueryString["accountname"] != null)
                    _userAccount = Request.QueryString["accountname"];
                UserProfileWS.UserProfileService profileService = new UserProfileWS.UserProfileService();
                UserProfileWS.PropertyData[] userProps = null;

                profileService.UseDefaultCredentials = true;
                userProps = profileService.GetUserProfileByName(_userAccount);
                StringBuilder sb = new StringBuilder();

                for (int i = 0; i < userProps.Length; i++)
                {
                    PropName = userProps[i].Name;
                    UserProfileWS.ValueData[] values = userProps[i].Values;

                    sb.AppendFormat("{0} : {1}", PropName, (values.Length > 0) ? values[0].Value.ToString() : "Error");
                    sb.AppendLine("<br />");
                }
                ltl_data.Text = sb.ToString();
            });
        }

        public void check_UserProperty(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                if(!string.IsNullOrEmpty(txt_userID.Text))
                    _userAccount = txt_userID.Text;
                UserProfileWS.UserProfileService profileService = new UserProfileWS.UserProfileService();
                UserProfileWS.PropertyData[] userProps = null;

                profileService.UseDefaultCredentials = true;
                userProps = profileService.GetUserProfileByName(_userAccount);
                StringBuilder sb = new StringBuilder();

                for (int i = 0; i < userProps.Length; i++)
                {
                    PropName = userProps[i].Name;
                    UserProfileWS.ValueData[] values = userProps[i].Values;

                    sb.AppendFormat("{0} : {1}", PropName, (values.Length > 0) ? values[0].Value.ToString() : "Null");
                    sb.AppendLine("<br />");
                }
                ltl_data.Text = sb.ToString();
            });
        }

        public void profileManagerClick(object sender, EventArgs e)
        {   
            UserProfileManagerTest();
        }

        public void sitecolleaguesgroup(object sender, EventArgs e)
        {
            UserColleaguesInfo();
        }

        public void UserProfileManagerTest()
        {
            strUrl = "http://gj2000j";  // 사이트 URL
            using (SPSite site = new SPSite(strUrl))
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    //SPServiceContext
                    SPServiceContext context = SPServiceContext.GetContext(site);
                    //ServerContext context = ServerContext.GetContext(site);
                    UserProfileManager upm = new UserProfileManager(context);

                    string accountName = txt_userID.Text;   // 사용자 계정 domain\UserId
                    UserProfile userProfile;
                    if (upm.UserExists(accountName))
                    {
                        userProfile = upm.GetUserProfile(accountName);

                        StringBuilder sb = new StringBuilder();

                        if (userProfile != null)
                        {
                            if (!string.IsNullOrEmpty(txt_userID.Text))
                                _userAccount = txt_userID.Text;
                            UserProfileWS.UserProfileService profileService = new UserProfileWS.UserProfileService();
                            UserProfileWS.PropertyData[] userProps = null;

                            profileService.UseDefaultCredentials = true;
                            userProps = profileService.GetUserProfileByName(_userAccount);

                            sb.Append("<table>");
                            sb.Append("<tr>");
                            sb.Append("<td>DisPlayName</td>");
                            sb.Append("<td>PropertyFieldName</td>");
                            sb.Append("<td>DataValue</td>");
                            sb.Append("</tr>");
                            for (int i = 0; i < userProps.Length; i++)
                            {
                                PropName = userProps[i].Name;
                                UserProfileWS.ValueData[] values = userProps[i].Values;
                                sb.Append("<tr>");
                                sb.AppendFormat("<td>{0}</td>", userProfile[PropName].ProfileSubtypeProperty.DisplayName);
                                sb.AppendFormat("<td>{0}</td>", PropName);
                                sb.AppendFormat("<td>{0}</td>", userProfile[PropName].Value != null ? userProfile[PropName].Value.ToString() : "No Data");
                                sb.Append("</tr>");
                            }
                            sb.Append("</table>");
                        }
                        ltl_data.Text = sb.ToString();
                    }
                });
            }
        }

        public void AddColleaguesMail()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                // The relationship should be two way, to add a colleague for another user we need to elevate
                using (SPSite site = new SPSite(strUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        // Impersonate the requesting user so we can add a friend relationship back
                        //SPUserToken reqToken = web.AllUsers[requestedProfile[UserProfileConstants.ACCOUNT_NAME].ToString()].UserToken;
                        SPUserToken reqToken = null;

                        // Create a site object inside this user's environment
                        // The relationship should be two way, to add a colleague for another user we need to elevate
                        using (SPSite impersSite = new SPSite(strUrl, reqToken))
                        {
                            site.AllowUnsafeUpdates = true;

                            using (SPWeb impersWeb = impersSite.OpenWeb())
                            {
                                SPServiceContext context = SPServiceContext.GetContext(impersSite);
                                HttpContext currentContext = HttpContext.Current;
                                HttpContext.Current = null;

                                UserProfileManager profManager = new UserProfileManager(context);
                                UserProfile impersUser = profManager.GetUserProfile(_reqUserId);
                                UserProfile impersTargetUser = profManager.GetUserProfile(_currentUserId);

                                impersUser.Colleagues.CreateWithoutEmailNotification(impersTargetUser, ColleagueGroupType.UserSpecified, "Colleagues", false, Privacy.Public);

                                HttpContext.Current = currentContext;
                            }
                        }
                    }
                }

            });
        }

        public void UserColleaguesInfo()
        {
            strUrl = "http://gj2000j";  // 사이트 URL
            using (SPSite site = new SPSite(strUrl))
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    //SPServiceContext
                    SPServiceContext context = SPServiceContext.GetContext(site);
                    //ServerContext context = ServerContext.GetContext(site);
                    UserProfileManager upm = new UserProfileManager(context);

                    string accountName = txt_userID.Text;   // 사용자 계정 domain\UserId
                    UserProfile userProfile;
                    if (upm.UserExists(accountName))
                    {
                        userProfile = upm.GetUserProfile(accountName);

                        StringBuilder sb = new StringBuilder();

                        if (userProfile != null)
                        {
                            if (!string.IsNullOrEmpty(txt_userID.Text))
                                _userAccount = txt_userID.Text;
                            
                            UserProfile[] impersUser = userProfile.Colleagues.GetCommonColleagues();
                            
                            sb.Append("<table>");
                            sb.Append("<tr>");
                            sb.Append("<td>ColleagueName</td>");
                            sb.Append("<td>ColleagueRecordID</td>");
                            sb.Append("<td>ColleagueGroupName</td>");
                            sb.Append("</tr>");
                            for (int i = 0; i < impersUser.Length; i++)
                            {
                                PropName = impersUser[i].DisplayName;

                                sb.Append("<tr>");
                                sb.AppendFormat("<td>{0}</td>", PropName);
                                sb.AppendFormat("<td>{0}</td>", impersUser[i].RecordId);
                                sb.AppendFormat("<td>{0}</td>", impersUser[i].Colleagues.GetGroupList());
                                sb.Append("</tr>");
                            }
                            sb.Append("</table>");
                        }
                        ltl_data.Text = sb.ToString();
                    }
                });
            }
        }
    }
}
